import 'package:flutter/material.dart';
import '../demo/ui_demo.dart';
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:flutter_nfc_reader/flutter_nfc_reader.dart';
import '../wonders/utils/helpers.dart';
import "dart:typed_data";
import 'dart:convert';
class MyDemo extends StatelessWidget implements Demo {
  MyDemo(this.title);
  @override
  final String title;
  @override
  Widget build(BuildContext context) {
    return new HomePage(
      title: this.title,
    );
  }
}

class HomePage extends StatefulWidget {
  final String title;
  HomePage({this.title});
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {

  String _result;
  NfcData _nfcData;
  @override
  void initState() {
    _result="";
    super.initState();
  }

  _readNFC() async{
   NfcData response;
    setState(() {
      _nfcData = NfcData();
      _nfcData.status = NFCStatus.reading;
      _result='正在读取。。。';
    });

    print('NFC: Scan started');

    try {
      print('NFC: Scan readed NFC tag');
      response=await FlutterNfcReader.read();
    } on PlatformException {
      print('NFC: Scan stopped exception');
    }
    setState(() {
      _nfcData = response;
      _result=_nfcData.content;
    });

  }
  _writeNFC() async{
    NfcData response1;
    NfcData response2;
    NfcData response3;
    String selectApdu1="00A404000F7378312E73682EC9E7BBE1B1A3D5CF";
    String selectApdu2="00A4000002EF05";
    String selectApdu3="00B2070409";
    String label1=_getLabel(selectApdu1);
    String label2=_getLabel(selectApdu2);
    String label3=_getLabel(selectApdu3);
    String res1;
    String res2;
    String res3;
    try {
      print('NFC: Scan write NFC tag');
     response1= await FlutterNfcReader.write("path1", label1);
     res1=formatBytesAsHexString(createUint8ListFromString(response1.content));
     print("res1:$res1");
     response2= await FlutterNfcReader.write("path2", label2);
      res2=formatBytesAsHexString(createUint8ListFromString(response2.content));
      print("res2:$res2");
     response3= await FlutterNfcReader.write("path13", label3);
      res3=formatBytesAsHexString(createUint8ListFromString(response3.content));
      print("res3:$res3");
    } on Exception catch(e) {
      print('NFC: Scan stopped exception:$e');
    }
    setState(() {
      String res1=formatBytesAsHexString(createUint8ListFromString(response1.content));
      String res2=formatBytesAsHexString(createUint8ListFromString(response2.content));
      String res3=formatBytesAsHexString(createUint8ListFromString(response3.content));
      _result='''
      res1:$res1
      res2:$res2
      res3:$res3
      ''';
    });
  }
  _getLabel(String apdu){
    List<int> selectBytes=createUint8ListFromHexString(apdu);
    return String.fromCharCodes(selectBytes);
  }
  _stopNFC() async{
    NfcData response;

    try {
      print('NFC: Stop scan by user');
      response = await FlutterNfcReader.stop();
    } on PlatformException {
      print('NFC: Stop scan exception');
      response = NfcData(
        id: '',
        content: '',
        error: 'NFC scan stop exception',
        statusMapper: '',
      );
      response.status = NFCStatus.error;
    }

    setState(() {
      _nfcData = response;
      _result='nfc stoped!';
    });
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text(widget.title),),
      body: Container(
        child: Center(
          child: Column(
            children: <Widget>[
              Expanded(
                flex: 4,
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: <Widget>[
                    OutlineButton(onPressed: _readNFC,child: Text("StartRead.."),),
                    OutlineButton(onPressed: _stopNFC,child: Text("StopRead.."),),
                    OutlineButton(onPressed: _writeNFC,child: Text("Write.."),),
                  ],
                ),
              ),
              Expanded(
                flex: 1,
                child: Text(_result),
              ),
            ],
          ),
        ),
      ),
    );
  }

  @override
  void dispose() {
    super.dispose();
  }
  Future requestPermission() async {
    // 申请权限
    Map<PermissionGroup, PermissionStatus> permissions =
    await PermissionHandler().requestPermissions([PermissionGroup.sensors,PermissionGroup.contacts]);
    // 申请结果
    PermissionStatus permission =
    await PermissionHandler().checkPermissionStatus(PermissionGroup.contacts);
    if (permission == PermissionStatus.granted) {
      print( "存储权限申请通过");
    } else {
      print( "存储权限申请被拒绝");
    }
  }
}
